package org.onvivals.app.ai.tts.model.chattts;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.onvivals.app.ai.tts.AbstractTtsService;
import org.onvivals.common.utils.FFmpegUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class ChatTtsService extends AbstractTtsService {

	private JSONObject ttsConfig;


	private static final Lock lock = new ReentrantLock();

	public ChatTtsService(JSONObject config) {
		this.ttsConfig = config;
	}
    public ChatTtsService() {
    }

    public static String generateFilePath() {
        lock.lock();
        try {
            String tmpDir = System.getProperty("java.io.tmpdir");
            String uniqueId = IdUtil.getSnowflakeNextIdStr();
            return tmpDir + uniqueId + ".mp3";
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Optional<String> speechSynthesizer(String id, String content) {
        String key = ttsConfig.getStr("key");
		ttsConfig.remove("key");
		ttsConfig.put("inputs",content);
		System.out.println(ttsConfig);
        HttpResponse response = HttpUtil.createPost("https://ai.gitee.com/api/serverless/ChatTTS/text-to-speech")
                .header("Authorization", "Bearer " + key)
                .body(ttsConfig.toString())
                .execute();
		if (response.isOk()){
			byte[] bytes = response.bodyBytes();
			String filePath = generateFilePath();
			File f = new File(filePath);
			FileUtil.writeBytes(bytes,f);
			String newFilePath = generateFilePath();
			FFmpegUtils.waveMaker(f.getAbsolutePath(), newFilePath);
			f.delete();
			return Optional.of(newFilePath);
		}else {
			log.error("ReechoTtsService error: {}", response.body());
		}
        return Optional.empty();
    }

    public static void main(String[] args) {
        String str = """
				{
				  "params_infer_code": {
				  "prompt": "[oral_1]",
				  "temperature": 0.3,
				  "top_P": 0.7,
				  "top_K": 20
				  },
				  "inputs": "The answer to the universe is 42"
				  }
                """;
        System.out.println(JSONUtil.toJsonStr(str));
        String key  = "RC7EFYEMPI5QHYWW9T8SE0MZ8MB8YTWLYHBZHTDM";
                HttpResponse response = HttpUtil.createPost("https://ai.gitee.com/api/serverless/ChatTTS/text-to-speech")
                .header("Authorization", "Bearer " + key)
                        .body(JSONUtil.toJsonPrettyStr(str))
                .execute();
               if (response.isOk()){
				   System.out.println();
				   byte[] bytes = response.bodyBytes();
				   String s = generateFilePath();
                   FileUtil.writeBytes(bytes,s);
                   System.out.println(s);
               }else {
				   log.error("ReechoTtsService error: {}", response.body());
			   }

    }

}
